<template>
  <el-dialog
    v-model="visible"
    title="修改密码"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      @submit.prevent
    >
      <!-- 旧密码 -->
      <el-form-item label="当前密码" prop="oldPassword">
        <el-input
          v-model="formData.oldPassword"
          type="password"
          placeholder="请输入当前密码"
          show-password
        />
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="formData.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
        <div class="password-tips">
          <p>密码必须包含：</p>
          <ul>
            <li :class="{ valid: passwordStrength.length }">
              <el-icon
                ><component
                  :is="passwordStrength.length ? 'CircleCheck' : 'CircleClose'"
              /></el-icon>
              至少8个字符
            </li>
            <li :class="{ valid: passwordStrength.number }">
              <el-icon
                ><component
                  :is="passwordStrength.number ? 'CircleCheck' : 'CircleClose'"
              /></el-icon>
              至少1个数字
            </li>
            <li :class="{ valid: passwordStrength.letter }">
              <el-icon
                ><component
                  :is="passwordStrength.letter ? 'CircleCheck' : 'CircleClose'"
              /></el-icon>
              至少1个字母
            </li>
            <li :class="{ valid: passwordStrength.special }">
              <el-icon
                ><component
                  :is="
                    passwordStrength.special ? 'CircleCheck' : 'CircleClose'
                  "
              /></el-icon>
              至少1个特殊字符
            </li>
          </ul>
        </div>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>

      <!-- 密码强度指示器 -->
      <el-form-item label="密码强度">
        <div class="strength-indicator">
          <div class="strength-bar">
            <div
              class="strength-progress"
              :style="{ width: `${strengthScore * 25}%` }"
              :class="strengthLevel"
            ></div>
          </div>
          <span class="strength-text" :class="strengthLevel">
            {{ strengthText }}
          </span>
        </div>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          :disabled="!isPasswordValid"
          @click="handleSubmit"
        >
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { CircleCheck, CircleClose } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

// 表单数据
const formRef = ref(null);
const formData = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单校验规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== formData.value.newPassword) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const formRules = {
  oldPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, message: "密码长度不能小于8个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

// 密码强度检查
const passwordStrength = computed(() => {
  const password = formData.value.newPassword;
  return {
    length: password.length >= 8,
    number: /\d/.test(password),
    letter: /[a-zA-Z]/.test(password),
    special: /[^a-zA-Z0-9]/.test(password),
  };
});

// 密码强度得分
const strengthScore = computed(() => {
  return Object.values(passwordStrength.value).filter(Boolean).length;
});

// 密码强度等级
const strengthLevel = computed(() => {
  const score = strengthScore.value;
  if (score === 0) return "none";
  if (score === 1) return "weak";
  if (score === 2) return "medium";
  if (score === 3) return "strong";
  return "very-strong";
});

// 密码强度文本
const strengthText = computed(() => {
  const textMap = {
    none: "无",
    weak: "弱",
    medium: "中",
    strong: "强",
    "very-strong": "很强",
  };
  return textMap[strengthLevel.value];
});

// 密码是否有效
const isPasswordValid = computed(() => {
  return (
    strengthScore.value >= 3 &&
    formData.value.newPassword === formData.value.confirmPassword
  );
});

// 加载状态
const loading = ref(false);

// 对话框可见性
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    // TODO: 调用修改密码API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    ElMessage.success("密码修改成功");
    emit("success");
    visible.value = false;
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理关闭
const handleClosed = () => {
  formRef.value?.resetFields();
  formData.value = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  };
};

// 监听密码变化
watch(
  () => formData.value.newPassword,
  (newVal) => {
    if (
      formData.value.confirmPassword &&
      newVal !== formData.value.confirmPassword
    ) {
      formRef.value?.validateField("confirmPassword");
    }
  },
);
</script>

<style lang="scss" scoped>
.password-tips {
  @apply mt-2 text-sm text-gray-500;

  ul {
    @apply mt-1 space-y-1;
  }

  li {
    @apply flex items-center text-gray-400;

    .el-icon {
      @apply mr-1;
    }

    &.valid {
      @apply text-green-500;
    }
  }
}

.strength-indicator {
  @apply flex items-center space-x-2;

  .strength-bar {
    @apply flex-1 h-2 bg-gray-200 rounded-full overflow-hidden;

    .strength-progress {
      @apply h-full transition-all duration-300;

      &.none {
        @apply bg-gray-300;
      }

      &.weak {
        @apply bg-red-500;
      }

      &.medium {
        @apply bg-yellow-500;
      }

      &.strong {
        @apply bg-green-500;
      }

      &.very-strong {
        @apply bg-primary-600;
      }
    }
  }

  .strength-text {
    @apply w-8 text-center text-sm;

    &.none {
      @apply text-gray-400;
    }

    &.weak {
      @apply text-red-500;
    }

    &.medium {
      @apply text-yellow-500;
    }

    &.strong {
      @apply text-green-500;
    }

    &.very-strong {
      @apply text-primary-600;
    }
  }
}

.dialog-footer {
  @apply flex justify-end space-x-2;
}
</style>
